from lxml import etree
from util.selenium.webdriver.common.by import By

from base.BaseMethod import BM
from util.DataQuery.FormDataDecorator import FormDataDecorator
from util.g import g


class IAStaDesc():
    parent_btn_loc = (By.LINK_TEXT, "企业创新能力")
    form_btn_loc = (By.LINK_TEXT, "科技成果转化情况")
    save_btn_loc = (By.CSS_SELECTOR, "button#dataEprCycxSave")
    # # # 添加删除按钮
    add_btn_loc = (By.CSS_SELECTOR, ".table-search button.blue")
    delete_btn_loc = (By.CSS_SELECTOR, ".table-search button.btn-default")
    sta_desc_loc = (By.CSS_SELECTOR, "textarea#Kjcgzh")

    # # # # # # # # # #  科技成果转化详细信息。
    sta_name_loc = (By.CSS_SELECTOR, "input#transName")
    sta_type_loc = (By.CSS_SELECTOR, "select#transTypeList")
    sta_source_loc = (By.CSS_SELECTOR, "select#transSourceList")
    trans_result_loc = (By.CSS_SELECTOR, "select#transResult")
    trans_date_loc = (By.CSS_SELECTOR, "input#transDate")
    trans_date_js_str = "document.getElementById('transDate').removeAttribute('readonly')"
    sort_num_loc = (By.CSS_SELECTOR, "input#position")
    # relevance 关联
    relevance_ip_loc = (By.CSS_SELECTOR, "textarea#yxtransIp")
    relevance_ip_js_str = "document.getElementById('yxtransIp').removeAttribute('readonly')"
    relevance_rd_loc = (By.CSS_SELECTOR, "textarea#yxtransRd")
    relevance_rd_js_str = "document.getElementById('yxtransRd').removeAttribute('readonly')"
    relevance_ps_loc = (By.CSS_SELECTOR, "textarea#yxtransPs")
    relevance_ps_js_str = "document.getElementById('yxtransPs').removeAttribute('readonly')"
    sta_ipr_loc = (By.CSS_SELECTOR, "select#transIp")
    sta_rd_loc = (By.CSS_SELECTOR, "select#transRd")
    sta_ps_loc = (By.CSS_SELECTOR, "select#transPs")
    sta_way_loc = (By.CSS_SELECTOR, "select#transWay")
    # # 转化方式
    trans_style_loc = (By.CSS_SELECTOR, "textarea#yxtransWay")
    trans_style_js_str = "document.getElementById('yxtransWay').removeAttribute('readonly')"
    upload_btn_loc = (By.CSS_SELECTOR, ".uploadAttachment a")
    # # 保存和返回按钮。
    detail_save_btn_loc = (By.CSS_SELECTOR, ".box-footer.text-right button#dataEprTransSave")
    back_btn_loc = (By.CSS_SELECTOR, ".box-footer.text-right .btn-default")

    page_num_loc = (By.CSS_SELECTOR, ".pagination.pull-right li:nth-of-type(3) a")

    next_page_loc = (By.CSS_SELECTOR, ".pagination.pull-right li:nth-of-type(4) a")

    select_all_loc = (By.CSS_SELECTOR, "input#items_selector")

    delete = False
    # 写代码时方便提示, 基本方法完成后删除
    # driver = driver
    def __init__(self, driver=None, text=""):
        self.driver = driver
        self.text = text
        setattr(g, self.class_name, dict())

    @property
    def class_name(self):
        return self.__class__.__name__

    #  这里把 填写 textarea 和 添加数据 方法分离。 WriteInnovationAbilityForm 实例化该对象时，需要调用两个方法。
    def fill_form(self):
        BM.click(driver=self.driver, ele_loc=self.form_btn_loc)
        BM.wait(driver=self.driver, ele_loc=self.sta_desc_loc)
        BM.input(driver=self.driver, ele_loc=self.sta_desc_loc, keys=self.text)

        BM.global_click_btn(btn_loc=self.save_btn_loc, driver=self.driver)

    def input_science_technology_achievement_info(self, sta_name, sta_type, sta_source, trans_result, trans_date, sort_num):
        BM.input(ele_loc=self.sta_name_loc, driver=self.driver, keys=sta_name)
        BM.select_value_choice(selector_loc=self.sta_type_loc, text_value=sta_type, driver=self.driver)
        BM.select_value_choice(selector_loc=self.sta_source_loc, text_value=sta_source, driver=self.driver)
        BM.select_value_choice(selector_loc=self.trans_result_loc, text_value=trans_result, driver=self.driver)
        self.driver.execute_script(self.trans_date_js_str)
        BM.input(ele_loc=self.trans_date_loc, driver=self.driver, keys=trans_date)
        BM.input(ele_loc=self.sort_num_loc, driver=self.driver, keys=sort_num)

    def input_textarea_info(self, ipr_ids, ipn_ids, rd_ids, ps_ids, trans_ids):
        if ipr_ids != "" and ipr_ids:
            for ip in ipr_ids.split(","):
                if not ip:
                    continue
                ip_s = "IP" + ip.zfill(2) if int(ip) != 0 else "其他"
                BM.select_value_choice(selector_loc=self.sta_ipr_loc, driver=self.driver, text_value=ip_s)
        if ipn_ids != "" and ipn_ids:
            for ipn in ipn_ids.split(","):
                if not ipn:
                    continue
                ipn_s = "NIP" + ip.zfill(2) if int(ip) != 0 else "其他"
                BM.select_value_choice(selector_loc=self.sta_ipr_loc, driver=self.driver, text_value=ipn_s)
        if rd_ids != "" and rd_ids:
            for rd in rd_ids.split(","):
                if not rd:
                    continue
                rd_s = "RD" + rd.zfill(2) if int(rd) != 0 else "其他"
                BM.select_value_choice(selector_loc=self.sta_rd_loc, driver=self.driver, text_value=rd_s)
        if ps_ids != "" and ps_ids:
            for ps in ps_ids.split(","):
                if not ps:
                    continue
                ps_s = "PS" + ps.zfill(2) if int(ps) != 0 else "其他"
                BM.select_value_choice(selector_loc=self.sta_ps_loc, driver=self.driver, text_value=ps_s)
        for tran in trans_ids.split("#"):
            if not tran:
                continue
            tran = tran.split("-")[0]
            BM.select_value_choice(selector_loc=self.sta_way_loc, driver=self.driver, text_value=tran)



    @FormDataDecorator
    def ia_sta_desc(self, id="", sta_name="", sta_type="", sta_source="", trans_result="", trans_date="", sort_num='', ipr_ids="", ipn_ids="", rd_ids="", ps_ids="", trans_ids="", oss_path=None):
        # science technology 科技
        # achievement 成果
        # TODO 这个id 在 上传附件时候需要使用

        # BM.click(driver=self.driver, ele_loc=self.parent_btn_loc)
        # BM.click(driver=self.driver, ele_loc=self.form_btn_loc)
        # if g.is_first_entry:
        #     pass
        try:
            is_click = False
            class_name = self.class_name
            if getattr(g, class_name) == {}:
                is_click = True
                # BM.click(driver=self.driver, ele_loc=self.parent_btn_loc)
                BM.click(driver=self.driver, ele_loc=self.form_btn_loc)
                a_list = getattr(g, class_name)
                table_loc = (By.CSS_SELECTOR, ".tableBody")
                tr_loc = (By.CSS_SELECTOR, ".tableBody tr td:nth-of-type(2)")
                id_loc = (By.CSS_SELECTOR, ".tableBody tr td:nth-of-type(10)")

                while True and g.repetition:
                    BM.wait(driver=self.driver, ele_loc=table_loc)
                    data = self.driver.find_elements(*tr_loc)
                    id_data = self.driver.find_elements(*id_loc)
                    for index, i in enumerate(data):
                        # 获取 标签中的 汉字
                        sta_name_str = i.text
                        id_str = id_data[index].text
                        a_list[id_str] = sta_name_str
                        # a_list.append(sta_name_str)

                    next_btn = BM.get_ele(driver=self.driver, ele_loc=self.next_page_loc)
                    onclick = next_btn.get_attribute("onclick")
                    # if onclick != None:
                    print("onclick: {}".format(onclick))
                    if not onclick:
                        # BM.click(driver=self.driver, ele_loc=self.next_page_loc)
                        break
                    else:
                        next_btn.click()
            li_list = getattr(g, class_name)
            # if sta_name in li_list and g.repetition:
            if str(sort_num) in li_list and li_list.get(str(sort_num)) == sta_name:
                return
            g.logger.info("{}： {}".format(class_name, li_list))

            # if g.repetition and not self.delete:
            #     BM.delete_all(driver=self.driver, page_num_loc=self.page_num_loc, select_all_loc=self.select_all_loc, delete_btn_loc=self.delete_btn_loc)
            #     self.delete = True
            # if not is_click:
            #     BM.click(driver=self.driver, ele_loc=self.parent_btn_loc)
            #     BM.click(driver=self.driver, ele_loc=self.form_btn_loc)

            # g.logger.info("{}： {}".format(class_name, li_list))
            BM.click(driver=self.driver, ele_loc=self.add_btn_loc)
            BM.wait(driver=self.driver, ele_loc=self.detail_save_btn_loc)
            self.input_science_technology_achievement_info(sta_name=sta_name, sta_type=sta_type, sta_source=sta_source, trans_result=trans_result, trans_date=trans_date, sort_num=sort_num)
            self.input_textarea_info(ipr_ids=ipr_ids, ipn_ids=ipn_ids, rd_ids=rd_ids,
                                     ps_ids=ps_ids, trans_ids=trans_ids)

            BM.click_upload_attach(btn_loc=self.upload_btn_loc, driver=self.driver, class_name=self.class_name, _id=id)
            res = BM.global_click_btn(driver=self.driver, btn_loc=self.detail_save_btn_loc)
            if res:
                li_list[str(sort_num)] = sta_name
            # TODO 上传附件
            # self.upload_attachment(upload_btn_loc=self.upload_btn_loc)

            # click_back_btn(btn_loc=self.back_btn_loc, driver=self.driver)
        except Exception as err:
            err_msg = "{} file:{} lines:{}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                   err.__traceback__.tb_lineno)
            raise Exception(err_msg)
